package com.ruoyi.controller;

import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.domain.ExTemplateMain;
import com.ruoyi.domain.ExTemplateSide;
import com.ruoyi.service.IExTemplateMainService;
import com.ruoyi.service.IExTemplateSideService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;

import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 实验模板主Controller
 * 
 * @author ruoyi
 * @date 2024-09-21
 */
@RestController
@RequestMapping("/system/tempmain")
public class ExTemplateMainController extends BaseController
{
    @Autowired
    private IExTemplateMainService exTemplateMainService;

    @Autowired
    private IExTemplateSideService exTemplateSideService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 查询实验模板主列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ExTemplateMain exTemplateMain)
    {
        //查询当前用户角色
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        List<SysRole> sysRoles = roleService.selectRolesByUserId(sysUser.getUserId());
        int flag = 0;
        for (SysRole sysRole : sysRoles) {
            if (sysRole.isFlag() == true && (sysRole.getRoleName().indexOf("管理员") > -1 || sysRole.getRoleName().indexOf("PI") > -1)){
                flag = 1;
            }
        }
        if (flag == 1){ //管理员查看所有的
            startPage();
            List<ExTemplateMain> list = exTemplateMainService.selectExTemplateMainList(exTemplateMain);
            for (ExTemplateMain templateMain : list) {
                ExTemplateSide exTemplateSide = new ExTemplateSide();
                exTemplateSide.setMainTableId(templateMain.getId());
                List<ExTemplateSide> exTemplateSides = exTemplateSideService.selectExTemplateSideList(exTemplateSide);
                templateMain.setSideTables(exTemplateSides);
            }
            return getDataTable(list);
        }else {  //学生查看自己的和系统的
            exTemplateMain.setCreatorId(loginUser.getUserId().toString());
            startPage();
            List<ExTemplateMain> list = exTemplateMainService.selectExTemplateMainListForStud(exTemplateMain);
            for (ExTemplateMain templateMain : list) {
                ExTemplateSide exTemplateSide = new ExTemplateSide();
                exTemplateSide.setMainTableId(templateMain.getId());
                List<ExTemplateSide> exTemplateSides = exTemplateSideService.selectExTemplateSideList(exTemplateSide);
                templateMain.setSideTables(exTemplateSides);
            }
            return getDataTable(list);
        }
    }

    /**
     * 导出实验模板主列表
     */
    @Log(title = "实验模板主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExTemplateMain exTemplateMain)
    {
        List<ExTemplateMain> list = exTemplateMainService.selectExTemplateMainList(exTemplateMain);
        ExcelUtil<ExTemplateMain> util = new ExcelUtil<ExTemplateMain>(ExTemplateMain.class);
        util.exportExcel(response, list, "实验模板主数据");
    }

    /**
     * 获取实验模板主详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        ExTemplateMain exTemplateMain = exTemplateMainService.selectExTemplateMainById(id);
        ExTemplateSide side = new ExTemplateSide();
        side.setMainTableId(id);
        List<ExTemplateSide> exTemplateSides = exTemplateSideService.selectExTemplateSideList(side);
        exTemplateMain.setSideTables(exTemplateSides);
        return success(exTemplateMain);
    }

    /**
     * 新增实验模板主
     */
    @Log(title = "实验模板主", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExTemplateMain exTemplateMain)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        String mainTbaleId = UUID.randomUUID().toString();
        List<ExTemplateSide> sideTables = exTemplateMain.getSideTables();
        exTemplateMain.setId(mainTbaleId);
        exTemplateMain.setCreatorId(sysUser.getUserId().toString());
        exTemplateMain.setCreatorName(sysUser.getNickName());
        //添加模板类型
        List<SysRole> sysRoles = roleService.selectRolesByUserId(sysUser.getUserId());
        int flag = 0;
        for (SysRole sysRole : sysRoles) {
            if (sysRole.isFlag() == true && (sysRole.getRoleName().indexOf("管理员") > -1 || sysRole.getRoleName().indexOf("PI") > -1)){
                flag = 1;
            }
        }
        if (flag == 1){
            exTemplateMain.setTemType("实验室模版");
        }else {
            exTemplateMain.setTemType("学生模板");
        }

        int index = 1;
        for (ExTemplateSide sideTable : sideTables) {
            sideTable.setMainTableId(mainTbaleId);
            sideTable.setStepNum(String.valueOf(index));
            exTemplateSideService.insertExTemplateSide(sideTable);
            index++;
        }

        return toAjax(exTemplateMainService.insertExTemplateMain(exTemplateMain));
    }

    /**
     * 拷贝为系统模板
     */
    @Log(title = "拷贝为系统模板", businessType = BusinessType.INSERT)
    @PostMapping("/toCopyXTMB")
    public AjaxResult toCopyXTMB(@RequestBody ExTemplateMain exTemplateMain)
    {
        ExTemplateMain exTemplateMain1 = exTemplateMainService.selectExTemplateMainById(exTemplateMain.getId());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        String mainTbaleId = UUID.randomUUID().toString();
        ExTemplateSide exTemplateSide = new ExTemplateSide();
        exTemplateSide.setMainTableId(exTemplateMain.getId());
        List<ExTemplateSide> sideTables = exTemplateSideService.selectExTemplateSideList(exTemplateSide);
        exTemplateMain1.setId(mainTbaleId);
        exTemplateMain1.setCreatorId(sysUser.getUserId().toString());
        exTemplateMain1.setCreatorName(sysUser.getNickName());
        exTemplateMain1.setTemType("实验室模版");
        int index = 1;
        for (ExTemplateSide sideTable : sideTables) {
            sideTable.setMainTableId(mainTbaleId);
            sideTable.setStepNum(String.valueOf(index));
            exTemplateSideService.insertExTemplateSide(sideTable);
            index++;
        }

        return toAjax(exTemplateMainService.insertExTemplateMain(exTemplateMain1));
    }

    /**
     * 修改实验模板主
     */
    @Log(title = "实验模板主", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExTemplateMain exTemplateMain)
    {
        //先删除字表
            ExTemplateSide exTemplateSide = new ExTemplateSide();
            exTemplateSide.setMainTableId(exTemplateMain.getId());
            List<ExTemplateSide> exTemplateSides = exTemplateSideService.selectExTemplateSideList(exTemplateSide);
        for (ExTemplateSide templateSide : exTemplateSides) {
            exTemplateSideService.deleteExTemplateSideById(templateSide.getId());
        }

        //再新增字表
        List<ExTemplateSide> sideTables = exTemplateMain.getSideTables();
        int index = 1;
        for (ExTemplateSide sideTable : sideTables) {
            sideTable.setMainTableId(exTemplateMain.getId());
            sideTable.setStepNum(String.valueOf(index));
            exTemplateSideService.insertExTemplateSide(sideTable);
            index++;
        }
        return toAjax(exTemplateMainService.updateExTemplateMain(exTemplateMain));
    }

    /**
     * 删除实验模板主
     */
    @Log(title = "实验模板主", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        for (String id : ids) {
                ExTemplateSide exTemplateSide = new ExTemplateSide();
                exTemplateSide.setMainTableId(id);
                List<ExTemplateSide> exTemplateSides = exTemplateSideService.selectExTemplateSideList(exTemplateSide);
                for (ExTemplateSide templateSide : exTemplateSides) {
                    exTemplateSideService.deleteExTemplateSideById(templateSide.getId());
                }
        }

        return toAjax(exTemplateMainService.deleteExTemplateMainByIds(ids));
    }
}
